//
//  CityViewController.m
//  Person
//
//  Created by kane on 14-9-26.
//  Copyright (c) 2014年 kane. All rights reserved.
//

#import "CityViewController.h"
#import "Database.h"


@interface CityViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    __weak IBOutlet UIButton *LBSButton;
    __weak IBOutlet UIScrollView *historyScroll;
    __weak IBOutlet UISearchBar *searchBar;
    __weak IBOutlet UITableView *searchTable;
    __weak IBOutlet UITableView *leftTable;
    __weak IBOutlet UITableView *rightTable;
    __weak IBOutlet UIButton *coverBtn;
    __weak IBOutlet UILabel *locationLabel;
    NSMutableArray *leftList;
    NSMutableDictionary *areaDict;
    NSMutableArray *indexList;
    NSMutableArray *historyList;
    NSMutableArray *searchList;
    NSMutableArray *searchCityList;
    
    
    BOOL bIsLBS;
    BOOL isSearch;
    int currentAreaID;
    
    
}

@end

@implementation CityViewController
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initData];
    [leftTable setSeparatorColor:[UIColor grayColor]];
    leftTable.sectionIndexBackgroundColor=[UIColor whiteColor];
    [leftTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [LBSButton setTitle:[UserEntity sharedUser].AreaName forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(synAddressSuccess) name:NotificationCityChanged object:nil];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [searchBar resignFirstResponder];
    [leftTable reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initData
{    
    areaDict = [[NSMutableDictionary alloc]init];
    searchList = [[NSMutableArray alloc] init];
    searchCityList = [[NSMutableArray alloc] init];
    NSArray *hostCity = [[NSArray alloc] initWithObjects:@"北京",@"重庆",@"广州",@"深圳",@"上海", nil];
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
                                                   ofType:@"plist"];
    
    areaDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    for (int i = 0; i < [[areaDict allValues] count]; i ++ ) {
        NSArray *temArr = [areaDict allValues][i];
        for (int j = 0; j < [temArr count]; j ++) {
            [searchCityList addObject:temArr[j]];
        }
    }
    indexList = [[NSMutableArray alloc] init];
    [indexList addObjectsFromArray:[[areaDict allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    //添加热门城市
    NSString *strHot = @"★";
    [indexList insertObject:strHot atIndex:0];
    [areaDict setObject:hostCity forKey:strHot];
    
}

- (void)synAddressSuccess
{
    [LBSButton setTitle:[UserEntity sharedUser].AreaName forState:UIControlStateNormal];
    if (bIsLBS) {
        [self performSelector:@selector(backBtnPressed:) withObject:nil afterDelay:0.5];
    }
}

#pragma mark - UIButton Events

- (IBAction)backBtnPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource && Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == leftTable) {
        return [indexList count] + 1;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == leftTable) {
        if (section == 0) {
            return 1;
        }
        return [[areaDict objectForKey:[indexList objectAtIndex:section-1]] count];
    }
    else if (tableView == searchTable){
        return [searchList count];
    }
    return 0;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 20.0;
//}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == leftTable) {
        
        UILabel *title = [[UILabel alloc] initWithFrame:(CGRect){0,0,fWidth_Current,20}];
        [title setText:[NSString stringWithFormat:@"    %@",section == 0 ? @"我的位置" : ([[indexList objectAtIndex:section-1] isEqualToString:@"★"] ? @"热门城市" : [indexList objectAtIndex:section-1])]];
        [title setBackgroundColor:BackColor];
        [title setFont:[UIFont systemFontOfSize:16]];
        [title setTextColor:BlueColor];
        return title;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == leftTable) {
//        if (currentAreaID == [[dic objectForKey:@"id"] intValue]) {
//            cell.backgroundColor = [UIColor whiteColor];
//        }else{
//            cell.backgroundColor = BackColor;
//        }
        cell.backgroundColor = [UIColor whiteColor];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        [cell.textLabel setTextColor:[UIColor blackColor]];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        
    }
    if (tableView == leftTable) {
        
        if (indexPath.section == 0) {
            NSString *temStr = @"GPS定位";
            NSString *text = [NSString stringWithFormat:@"%@ %@  %@",[UserEntity sharedUser].ProvinceName,[UserEntity sharedUser].CityName,temStr];
            NSMutableAttributedString *attributedStr1 = [[NSMutableAttributedString alloc]initWithString:text];
            [attributedStr1 addAttribute:NSForegroundColorAttributeName
                                   value:[UIColor grayColor]
                                   range:NSMakeRange(text.length - temStr.length, temStr.length)];
            [attributedStr1 addAttribute:NSFontAttributeName
                                   value:[UIFont boldSystemFontOfSize:13]
                                   range:NSMakeRange(text.length - temStr.length, temStr.length)];
            cell.textLabel.attributedText = attributedStr1;
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
        }
        else {
            cell.textLabel.text = [[areaDict objectForKey:[indexList objectAtIndex:indexPath.section - 1]] objectAtIndex:indexPath.row];
        }

    }
    else {
        cell.textLabel.text = [searchList objectAtIndex:indexPath.row];
    }
    return cell;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == leftTable) {
        return indexList;
    }
    return nil;
}

////响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (tableView == leftTable) {
        //点击索引，列表跳转到对应索引的行
        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index+1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        return index+1;

    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
       [[NSNotificationCenter defaultCenter] postNotificationName:NotificationCityChanged object:_currentCity];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        NSString *chooseCity = [[areaDict objectForKey:[indexList objectAtIndex:indexPath.section-1]] objectAtIndex:indexPath.row];
        [UserEntity sharedUser].selectCity = chooseCity;
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationCityChanged object:chooseCity];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UISearchBar Delegate

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
//{
//    leftTable.hidden = YES;
//    searchTable.hidden = NO;
//    return YES;
//}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        leftTable.hidden = NO;
        searchTable.hidden = YES;
        [leftTable reloadData];
    }else {
        
        leftTable.hidden = YES;
        searchTable.hidden = NO;
        [searchList removeAllObjects];
        [searchCityList enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL *stop) {
           if([str containsString:searchText])
              [searchList addObject:str];
        }];
        [searchTable reloadData];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)_searchBar;
{
    [searchBar endEditing:YES];
    [searchList removeAllObjects];
    [searchCityList enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL *stop) {
        if([str containsString:_searchBar.text])
            [searchList addObject:str];
    }];
    [searchTable reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (searchBar.text.length == 0) {
        [searchBar resignFirstResponder];
    }
}
@end
